import random
import redis
from flask import make_response
import json
from flask import Blueprint, request, jsonify
from Laboratory.app import db
from Laboratory.models.user import UsersModel
from Laboratory.util.captcha.captcha import captcha
from Laboratory.util.comm import send_message
from Laboratory.util.myredis import r
import time

user_blue = Blueprint("user", __name__)

@user_blue.route("/test")
def test():
    time.sleep(3)
    return jsonify({"code": 200, "mes": "mes"})

@user_blue.route('/getcode')
def get_img():
    name, text, img = captcha.generate_captcha()
    uuid = request.args.get('uuid')
    r.str_setex(uuid, text, 300)
    cls = redis.Redis(host='127.0.0.1')
    print(">>>>>>>>>>>>>>>>", cls.get(uuid))
    res = make_response(img)
    res.headers['Content-Type'] = "image/jpg"
    return res

# 发送短信接口
@user_blue.route("/sendSmsCode", methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
        uuid = data["uuid"]
        mobile = data["mobile"]
        image_code = data["image_code"]
        code = r.str_get(mobile)
        if code:
            if int(code) == int(image_code):
                user = UsersModel.query.filter(UsersModel.mobile == mobile).first()
                if user:
                    r.del_key(mobile)
                else:
                    u = UsersModel(mobile=mobile, nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                    user = UsersModel.query.filter(UsersModel.mobile == mobile).first()
                # token = myjwt.jwt_encode({"user_id":user.id,'exp':int(time.time())+60})
                token = str(random.randint(100, 1000))
                return jsonify({"code": 200, "msg": "发送成功", "token": token, "userid": user.id})
        else:
            return jsonify({"code": 10021, "mes": "验证码不存在"})
    else:
        return jsonify({"code": 10020, "mes": "数据不完整"})

@user_blue.route("/login", methods=["POST"])
def sendSmsCode():
    data = request.data
    # 获取3个参数
    if data:
        data = json.loads(data)
        uuid = data['uuid']
        sms_code = data['sms_code']
        print(sms_code, '>>>>>>>>>>>>>>>>')
        mobile = data['mobile']
        value = r.str_get(uuid)
        value1 = value.decode()
        print(value1)
        if value:
            if sms_code.lower() == value1.lower():
                mcode = r.str_get(mobile)
                if mcode:
                    return jsonify({'code': 10012, 'msg': '一分钟内不能重复发'})
                scode = random.randint(10000, 99999)
                flag = send_message(mobile, scode)
                if flag:
                    r.str_setex(mobile, scode, 60)
                    r.del_key(uuid)
                    return jsonify({'code': 200, 'msg': '发送成功'})
                else:
                    return jsonify({'code': 10013, 'msg': '发送验证码错误'})
            else:
                return jsonify({'code': 10011, 'msg': '图片验证码错误'})
        else:
            return jsonify({'code': 10010, 'msg': '图片验证码不存在'})


